import { useState, useEffect } from 'react';
import { Button, message } from 'antd';
import { FormPro } from '@/components';
import { FormInstance } from 'antd/lib/form';
import React, { useRef, useCallback } from 'react';
import { FormItem } from '@/components/FormPro/types';
import userRewards from '@/service/rewards';
import recordToNum from '@/utils/recordToNum';
import getDetail from '@/service/rewards/getDetail';
import styles from './styles.less';

const formList: FormItem[] = [
  {
    type: 'input',
    name: 'users',
    label: '邀请用户数',
    rules: [{
      required: true,
      message: '请输入邀请用户数',
    }, {
      pattern: /(^[1-9]\d*$)/,
      message: '邀请用户数只能为正整数',
    }],
  },
  {
    type: 'input',
    name: 'days',
    label: '奖励会员天数',
    rules: [{
      required: true,
      message: '请输入奖励会员天数',
    }, {
      pattern: /(^[1-9]\d*$)/,
      message: '奖励会员天数只能为正整数',
    }],
  },
];

const Settings = () => {
  const [loading,setLoading] = useState<boolean>(false);
  const formRef = useRef<FormInstance>();
  const onSubmit = useCallback(async () => {
    const fields = await formRef.current?.validateFields();
    setLoading(true)
    try {
      await userRewards(recordToNum(fields));
      message.success('保存成功');
    } catch (e) {
      message.error('保存失败');
    }
    setLoading(false);
  }, []);

  const fetchDetail = useCallback(() => {
    getDetail().then((res: any) => {
      formRef.current?.setFieldsValue({
        days: res?.days,
        users: res?.users
      });
    });
  }, []);


  useEffect(() => {
    fetchDetail();
  }, [fetchDetail]);

  return (
    <div className={styles.container}>
      <FormPro
        formList={formList}
        ref={(e: FormInstance) => formRef.current = e}
      />
      <div className={styles.footer}>
        <Button type="primary" onClick={onSubmit} loading={loading}>
          保存设置
        </Button>
      </div>
    </div>
  );
};

export default Settings;
